<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索 -->
          <el-input placeholder="请输入内容" class="input-with-select" v-model="info.query" clearable @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table border stripe :data="userList">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username" width="200px"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChangeFn(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column label="操作">
          <!-- 通过作用域插槽获取表单的数据 -->
          <!-- 通过结构赋值获取scope中row数据 -->
          <template v-slot='{row}'>
            <!-- 修改 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEdit(row)"></el-button>
            <!-- 删除 -->
            <el-button v-if="row.id!==500" type="danger" size="mini" icon="el-icon-delete" @click="remove(row.id)">
            </el-button>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable='false'>
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRole(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="info.pagenum"
        :page-sizes="[1, 2, 5, 10]" :page-size="info.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
      <el-form label-width="70px" :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%" @close='resetEditForm'>
      <el-form label-width="70px" :model="editForm" :rules="addFormRules" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" @close='selected = null'>
      <div>
        <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selected" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义邮箱校验规则
    const checkEmail = function (rule, value, callback) {
      const reg = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (reg.test(value)) {
        // callback() 校验通过
        callback()
      } else {
        // callback(new Error())校验失败
        callback(new Error('邮箱不符合格式'))
      }
    }
    // 自定义手机号校验规则
    const checkMobile = function (rule, value, callback) {
      const reg = /^1[3456789]\d{9}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号不符合格式'))
      }
    }
    return {
      // 下拉列表value
      selected: null,
      // 所有角色数据列表
      rolesList: [],
      // 需要分配角色的基本信息
      userInfo: {},
      // 分配角色对话框显示状态
      roleDialogVisible: false,
      // 修改用户对话框显示状态
      editDialogVisible: false,
      // 修改用户的表单数据
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 请求用户列表数据的参数
      info: {
        // 查询参数
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 5
      },
      // 存储用户列表数据
      userList: [],
      // 数据总条数
      total: 0,
      // 添加用户对话框显示状态
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 分配角色确定按钮点击事件
    async saveRoleInfo () {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selected })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.roleDialogVisible = false
      this.getUserList()
    },
    // 分配角色
    async setRole (row) {
      this.userInfo = row
      this.roleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    // 删除用户
    remove (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 提交修改表单
    saveEditForm () {
      this.$refs.editFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        // 关闭对话框
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 关闭编辑对话框清空
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击修改按钮触发
    showEdit (row) {
      // 显示修改对话框
      this.editDialogVisible = true
      // 把数据填充到对话框
      this.editForm = row
    },
    // 提交添加表单
    saveAddForm () {
      // 发送ajax前预校验
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加成功')
        // 关闭对话框
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 关闭时清空表单
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.info })
      this.total = res.data.total
      this.userList = res.data.users
    },
    // 监听pagesize改变
    handleSizeChange (size) {
      this.info.pagesize = size
      this.getUserList()
    },
    // 监听pagenum改变
    handleCurrentChange (num) {
      this.info.pagenum = num
      this.getUserList()
    },
    // 监听开关改变
    async stateChangeFn (info) {
      const { data: res } = await this.$http.put(`users/${info.id}/state/${info.mg_state}`)
      if (res.meta.status !== 200) {
        info.mg_state = !info.mg_state
        this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getUserList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-table {
  margin: 10px 0;
}
</style>
